import React, { Component } from 'react'
import './Task.scss'
import { Tag, Button, Table, Popconfirm, Modal, Form,Input, DatePicker,message } from 'antd'
import {getTaskList,addTask,removeTask,completeTask} from '../api/index'
const formattime = function (time) {
  let arr = time.match(/\d+/g);
  let [, month, day, hours, minutes] = arr
  return `${month}-${day} ${hours}:${minutes}`

}

class Task extends Component {
  /* 定义表格列的数据 */
  columns = [
    {
      title: "编号",
      dataIndex: 'id',
      align:'center',
      width:'8%'
    },
    {
      title: "任务描述",
      dataIndex: 'task',
      width:'50%'
    },
    {
      title: "状态",
      dataIndex: 'state',
      align:'center',
      width:'10%',
      render: state=>+state===1?'未完成':'已完成'
    },
    {
      title: "完成时间",
      dataIndex: "time",
      align:'center',
      width:'15%',
      render: (_, record) => {
        let { state, time, complete } = record
        if (+state === 2) time = complete;
        return formattime(time)
      }
    },
    {
      title: "操作",
      render: (_, record) => {
        let { id,state } = record
        return <>
          <Popconfirm title="您确认要删除此任务吗" onConfirm={() => {
            this.deleteTask(id)
          }}>
            <Button type='link'>删除</Button>
          </Popconfirm>

          {+state !== 2 ? <Popconfirm title='您确定要完成此任务吗' onConfirm={() => {
            this.finishTask(id)

          }}>
            <Button type='link' >完成</Button>
          </Popconfirm> : null
          }

        </>

      }
    }

  ]

  state = {
    tableData: [],
    tableLoading: false,
    isModalOpen:false,
    confirmLoading:false,
    selectedIndex:0
  }
  //获取服务器数据
  queryData=async()=>{
    let {selectedIndex}= this.state
    try{
      this.setState({tableLoading:true})
      let {code,list}=await getTaskList(selectedIndex)
      if(+code!==0) list=[]    
      this.setState({
        tableData:list
      })
    }catch(_){

    }
    this.setState({
      tableLoading:false
    })
  }
  selectedIndexData=(index)=>{
    if(this.state.selectedIndex===index) return;
    this.setState({
      selectedIndex:index
    },()=>{
      this.queryData()
    })
  }
  componentDidMount(){
    this.queryData()
  }
  //控制对话框, 清楚表单内容
  //关闭对话框,并且清楚表单内容
  controlModal=(status)=>{
    if(status){
      this.setState({
        isModalOpen:status
      })
    }
    if(!status){ 
    this.setState({
        isModalOpen:status,
        confirmLoading:status
      })
      this.formIns.resetFields()
    }
  }
  //新增任务
  submit=async()=>{
    try{
      //校验数据,返回的是promise对象
      await this.formIns.validateFields();
      //获取表单数据
      let {task,time}=this.formIns.getFieldsValue()
      time=time.format("YYYY-MM-DD HH:mm:ss")
      //跟服务器交互,异步要加await
      this.setState({
        confirmLoading:true
      })
      let {code} = await addTask(task,time)
      if(+code===1){
          message.error("添加失败")
      }else{
          this.controlModal(false)
          message.success("添加成功")
          this.queryData()
      }     
    }catch(_){
      message.error("填写错误或者未填写")
    }
     this.setState({
        confirmLoading:false
      }) 
  }
  //删除任务
  deleteTask=async(id)=>{
    try{
      let {code}=await removeTask(id)
      if(+code===0){
        message.success("删除成功")
        this.queryData()
      }else{
        message.error('删除失败')
      }
    }catch(_){}
  }
  //完成任务
  finishTask=async(id)=>{
    try{
      let {code} =await completeTask(id)
      if(+code===0){
        message.success('任务完成')
        this.queryData()
      }else{
        message.error('任务完成失败')
      }
    }catch(_){

    }
  }


  render() {
    let { tableData, tableLoading,isModalOpen,confirmLoading,selectedIndex } = this.state
    return (
      <div className='task-box'>
        {/* {头部} */}
        <div className="header">
          <h2 className="title">TASK OA任务管理系统</h2>
          <Button type='primary' onClick={this.controlModal.bind(null,true)}>新增任务</Button>
        </div>
        {/* 标签 */}
        <div className="tag-box">
          {/* 通过循环建立Tag标签 */}
            {
              ['全部','未完成','已完成'].map((data,index)=>{
               return <Tag key={index} color={selectedIndex===index?'#1677ff':''}
               onClick={()=>{this.selectedIndexData(index)}}>{data}</Tag>                
              })
            }
        </div>
        {/* 表格 */}
        <Table dataSource={tableData} columns={this.columns} loading={tableLoading} rowKey='id' pagination={false} />

        {/* 对话框 & 表单*/}
        <Modal 
        title="新增任务窗口"
        keyboard={false}
        maskClosable={false} 
        open={isModalOpen} 
        onCancel={this.controlModal.bind(null,false)} 
        onOk={this.submit} 
        confirmLoading={confirmLoading}
        okText="确认提交"
        >
         <Form layout='vertical'
          ref={x=>this.formIns=x}
         >
          <Form.Item label="任务描述" name='task' validateTrigger="onBlur" 
          rules={[
            {required:true,message:"任务描述必填"},
            {min:6,message:"至少输入6位以上"}
          ]} >
            <Input.TextArea rows={4}></Input.TextArea>
          </Form.Item>
          <Form.Item label="预期完成时间" name='time' validateTrigger="onBlur" 
          rules={[
            {required:true,message:"预期完成时间为必填项"}
          ]} >
            <DatePicker showTime/>
          </Form.Item>
         </Form>
        </Modal>
      </div>
    )
  }
}
export default Task
